<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { TranslationService } from '../services/translationService'
import { useLanguageStore } from '@/stores/language'
import { storeToRefs } from 'pinia'

const languageStore = useLanguageStore()
const { currentLanguage } = storeToRefs(languageStore)

const router = useRouter()
const searchText = ref('')

const blogList = ref([
  {
    id: 1,
    title: '技术创新与未来发展',
    date: '2024年1月15日',
    author: '张明',
    summary: '探讨技术创新如何改变我们的生活，以及未来发展趋势。',
  },
  {
    id: 2,
    title: '人工智能的未来展望',
    date: '2024年1月10日',
    author: '李华',
    summary: '深入分析人工智能技术的发展方向和潜在影响。',
  },
  {
    id: 3,
    title: '可持续发展与环保科技',
    date: '2024年1月5日',
    author: '王芳',
    summary: '探讨环保科技在可持续发展中的重要性。',
  },
])

const goToBlog = (id: number) => {
  router.push(`/blog/${id}`)
}

const originalOptions = [
  {
    value: 'all',
    label: '全部分类',
  },
  {
    value: 'tech',
    label: '技术创新',
  },
  {
    value: 'ai',
    label: '人工智能',
  },
  {
    value: 'env',
    label: '环境科技',
  },
]

const categoryOptions = ref([...originalOptions])

const selectedCategory = ref('all')

// 添加 placeholders 响应式对象
const placeholders = ref({
  title: '请输入标题',
  author: '请输入作者',
  summary: '请输入摘要',
})

// 修改 watch 函数，添加对 placeholders 的翻译
watch(
  () => currentLanguage.value,
  async (newLocale) => {
    if (newLocale && newLocale !== 'zh') {
      // 翻译分类选项
      categoryOptions.value = await Promise.all(
        originalOptions.map(async (option) => ({
          ...option,
          label: await TranslationService.translateText(option.label, newLocale),
        })),
      )

      // 翻译 placeholders
      const translations = await TranslationService.translateBatch(
        Object.values(placeholders.value),
        newLocale,
      )

      let index = 0
      for (const key in placeholders.value) {
        placeholders.value[key as keyof typeof placeholders.value] =
          translations[Object.values(placeholders.value)[index++]]
      }
    } else {
      categoryOptions.value = [...originalOptions]
      // 重置为中文 placeholders
      placeholders.value = {
        title: '请输入标题',
        author: '请输入作者',
        summary: '请输入摘要',
      }
    }
  },
  { immediate: true, deep: true },
)

const handleSearch = async () => {
  let messageText = `${searchText.value}`

  // 如果不是中文环境，先翻译成中文
  if (localStorage.getItem('locale') !== 'zh') {
    try {
      messageText = await TranslationService.translateText(messageText, 'zh')
    } catch (error) {
      console.error('翻译搜索消息失败:', error)
    }
  }

  ElMessage({
    message: messageText,
    type: 'success',
  })
}

const handleCategoryChange = async (value: string) => {
  // 获取原始的中文标签
  const originalLabel = originalOptions.find((opt) => opt.value === value)?.label
  let messageText = `已选择分类: ${originalLabel}`

  // 如果不是中文环境，先翻译消息
  if (localStorage.getItem('locale') !== 'zh') {
    try {
      messageText = await TranslationService.translateText(messageText, 'zh')
    } catch (error) {
      console.error('翻译分类消息失败:', error)
    }
  }

  ElMessage({
    message: messageText,
    type: 'success',
  })
}

// 添加表单数据
const formData = reactive({
  title: '',
  author: '',
  summary: '',
})

// 添加批量翻译方法
const handleBatchTranslate = async () => {
  if (!formData.title && !formData.author && !formData.summary) {
    const warningMsg =
      currentLanguage.value === 'zh'
        ? '请至少填写一个字段'
        : await TranslationService.translateText('请至少填写一个字段', currentLanguage.value)

    ElMessage({
      message: warningMsg,
      type: 'warning',
    })
    return
  }

  // 收集需要翻译的文本
  const textsToTranslate = []
  if (formData.title) textsToTranslate.push(formData.title)
  if (formData.author) textsToTranslate.push(formData.author)
  if (formData.summary) textsToTranslate.push(formData.summary)

  try {
    // 调用批量翻译API
    const translations = await TranslationService.translateBatch(textsToTranslate, 'zh')

    // 更新表单数据
    let index = 0
    const sendData = { ...formData }
    if (formData.title) sendData.title = translations[textsToTranslate[index++]]
    if (formData.author) sendData.author = translations[textsToTranslate[index++]]
    if (formData.summary) sendData.summary = translations[textsToTranslate[index]]

    console.log('表单上传:', sendData)

    ElMessage({
      message: `上传成功`,
      type: 'success',
    })
  } catch (error) {
    console.error('批量翻译失败:', error)

    const errorMsg =
      currentLanguage.value === 'zh'
        ? '批量翻译失败'
        : await TranslationService.translateText('批量翻译失败', currentLanguage.value)

    ElMessage({
      message: errorMsg,
      type: 'error',
    })
  }
}
</script>

<template>
  <div class="blog-list">
    <h1>技术博客</h1>

    <div class="filter-section">
      <el-select v-model="selectedCategory" class="category-select" @change="handleCategoryChange">
        <el-option
          v-for="item in categoryOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-input v-model="searchText" class="search-input">
        <template #append>
          <el-button @click="handleSearch"> 搜索 </el-button>
        </template>
      </el-input>
    </div>

    <div class="blog-grid">
      <div v-for="blog in blogList" :key="blog.id" class="blog-card" @click="goToBlog(blog.id)">
        <h2>{{ blog.title }}</h2>
        <div class="blog-meta">
          <span>{{ blog.date }}</span>
          <span>{{ blog.author }}</span>
        </div>
        <p class="blog-summary">{{ blog.summary }}</p>
      </div>
    </div>

    <!-- 添加批量翻译表单 -->
    <div class="translation-form">
      <h2>批量翻译表单</h2>
      <el-form :model="formData" label-width="120px">
        <el-form-item label="标题">
          <el-input v-model="formData.title" :placeholder="placeholders.title" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="formData.author" :placeholder="placeholders.author" />
        </el-form-item>
        <el-form-item label="摘要">
          <el-input
            v-model="formData.summary"
            type="textarea"
            rows="3"
            :placeholder="placeholders.summary"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleBatchTranslate"> 批量翻译成中文 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.filter-section {
  max-width: 600px;
  margin: 0 auto 30px;
  display: flex;
  gap: 15px;
}

.category-select {
  width: 150px;
  background-color: #505050;
}

:deep(.el-select .el-select__wrapper) {
  background-color: #2d2d2d;
}

:deep(.el-select .el-input__wrapper) {
  background-color: #2d2d2d;
}

:deep(.el-select .el-input__inner) {
  color: #d0d0d0;
}

:deep(.el-select-dropdown__item) {
  color: #d0d0d0;
}

:deep(.el-select-dropdown__item.hover) {
  background-color: #404040;
}

:deep(.el-select-dropdown) {
  background-color: #2d2d2d;
  border-color: #505050;
}

.search-section {
  max-width: 600px;
  margin: 0 auto 30px;
}

.search-input {
  width: 100%;
}

:deep(.el-input__wrapper) {
  background-color: #2d2d2d;
}

:deep(.el-input__inner) {
  color: #d0d0d0;
}

:deep(.el-input-group__append) {
  background-color: #404040;
  border-color: #505050;
}

.blog-list {
  max-width: 1200px;
  margin: 40px auto;
  padding: 0 20px;
}

h1 {
  color: #fff;
  text-align: center;
  margin-bottom: 40px;
}

.blog-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.blog-card {
  background: #2d2d2d;
  padding: 20px;
  border-radius: 8px;
  cursor: pointer;
  transition:
    transform 0.2s,
    box-shadow 0.2s;
}

.blog-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.blog-card h2 {
  color: #fff;
  margin-bottom: 10px;
  font-size: 1.4em;
}

.blog-meta {
  color: #a0a0a0;
  font-size: 0.9em;
  margin-bottom: 15px;
  display: flex;
  gap: 15px;
}

.blog-summary {
  color: #d0d0d0;
  line-height: 1.6;
}

.translation-form {
  max-width: 800px;
  margin: 40px auto;
  padding: 20px;
  background: #2d2d2d;
  border-radius: 8px;
}

.translation-form h2 {
  color: #fff;
  margin-bottom: 20px;
  text-align: center;
}

:deep(.el-form-item__label) {
  color: #d0d0d0;
}

:deep(.el-textarea__inner) {
  background-color: #2d2d2d;
  color: #d0d0d0;
}
</style>
